let express = require('express')
let fs = require('fs').promises
const JWT = require('simple-jwt');
const header = {
  typ: 'JWT',
  alg: 'HS512'
};
const secret = 'secret';
let bodyParser = require('body-parser')
let app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static('./assets'))

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', "*")// 设置响应头 支持跨域
  res.setHeader("Access-Control-Allow-Headers", 'Content-Type,Content-Length,Authorization, Accept,X-Requested-With,account,Authorization,a,test_token')
  // 所有的请求 从过来到离开 中间都会执行 中间件
  next()
})
app.listen(9000, function () {
  console.log("服务起于9000")
})
app.use(async function (req, res, next) {
  //  负责读取user  然后放到请求对象中
  let userStr = await fs.readFile('./json/user.json', 'utf-8')
  req.userAry = JSON.parse(userStr)

  let listStr = await fs.readFile('./json/list.json', 'utf-8')
  req.listAry = JSON.parse(listStr)
  next()
})

app.post('/register', function (req, res) {
  // 获取前端传递的用户名密码 然后存储到 json的user.json
  // 先读  在修改  修改完了在写入
  let res2 = req.userAry.some(item => item.name == req.body.name)
  if (res2) {
    res.send({
      code: 501,
      msg: "用户已存在"
    })
    return
  }
  let ary = req.userAry.concat(req.body)
  fs.writeFile('./json/user.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: '恭喜注册成功'
    })
  })

})
app.post('/login', function (req, res) {
  // 获取前端传递的用户名密码 然后存储到 json的user.json
  // 先读  在修改  修改完了在写入
  req.body
  let res2 = req.userAry.some(item => item.name == req.body.name && item.psw == req.body.psw)
  if (res2) {
    // 证明可以登录
    const token = JWT.getToken(header, {
      userName: req.body.name,
      psw: req.body.psw
    }, secret);
    res.send({
      code: 200,
      token: token
    })
  } else {
    res.send({
      code: 502,
      msg: '用户名密码不对'
    })
  }
})
function isLogin(req, res) {
  // true 登录； false没登陆
  let { payload } = JWT.decodeTokenHeaderAndPayload(req.headers.test_token)
  // 解析前端传过来的token  ; 校验是否是正常的登录状态
  console.log(payload)
  return req.userAry.some(item => item.name == payload.userName && item.psw == payload.psw)
}

app.get('/list', function (req, res) {
  let isL = isLogin(req, res)
  if (isL) {
    res.send({
      code: 200,
      data: req.listAry
    })
  } else {
    res.send({
      code: 501,
      msg: '未登录'
    })
  }

})
app.post('/add', (req, res) => {
  let ary = req.listAry;
  console.log('req.body', req.body)
  ary.push(req.body)
  fs.writeFile('./json/list.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: 'ok'
    })
  })
  // res.send('ok')
})
app.get('/del', (req, res) => {
  // console.log(req, req.query.id)
  let ary = req.listAry.filter(item => item.id != req.query.id)
  fs.writeFile('./json/list.json', JSON.stringify(ary), 'utf-8').then(data => {
    res.send({
      code: 200,
      msg: 'ok'
    })
  })
})